package com.lxl.xm.controller;

import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.lxl.xm.common.BaseResponse;
import com.lxl.xm.common.DeleteRequest;
import com.lxl.xm.common.ErrorCode;
import com.lxl.xm.common.ResultUtils;
import com.lxl.xm.exception.BusinessException;
import com.lxl.xm.model.dto.student_task.StudentTaskAddRequest;
import com.lxl.xm.model.dto.task.TaskAddRequest;
import com.lxl.xm.model.dto.task.TaskQueryRequest;
import com.lxl.xm.model.dto.task.TaskUpdateRequest;
import com.lxl.xm.model.entity.StudentTask;
import com.lxl.xm.model.entity.Task;
import com.lxl.xm.model.entity.TaskBranch;
import com.lxl.xm.model.vo.TaskCompleteVO;
import com.lxl.xm.model.vo.TaskVO;
import com.lxl.xm.service.TaskBranchService;
import com.lxl.xm.service.TaskService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.List;
import java.util.stream.Collectors;

@RestController
@RequestMapping("/task")
@Slf4j
public class TaskController {


    @Resource
    TaskService taskService;

    @Resource
    TaskBranchService taskBranchService;


    /**
     * 创建任务
     *
     * @param taskAddRequest
     * @param request
     * @return
     */
    @PostMapping("/add")
    public BaseResponse<Long> addTask(@RequestBody TaskAddRequest taskAddRequest, HttpServletRequest request) {
        if (taskAddRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Task task = new Task();
        BeanUtils.copyProperties(taskAddRequest, task);
        //参数校验
        taskService.validTask(task, true);
        //获取登录的用户id
        //User loginUser = userService.getLoginUser(request);
        //task.setUserId(loginUser.getId());
        boolean result = taskService.save(task);
        // 抛异常
        if (!result){
            throw new BusinessException(ErrorCode.OPERATION_ERROR,"添加失败");
        }
        long newTaskId = task.getId();
        // 返回任务的id
        return ResultUtils.success(newTaskId);
    }

    /**
     * 删除任务
     *
     * @param deleteRequest
     * @param request
     * @return
     */
    @PostMapping("/delete")
    public BaseResponse<Boolean> deleteTask(@RequestBody DeleteRequest deleteRequest, HttpServletRequest request) {
        if (deleteRequest == null || deleteRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        //User user = userService.getLoginUser(request);
        long id = deleteRequest.getId();
        // 判断是否存在
        Task oldTask = taskService.getById(id);
        if (oldTask == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        // 仅本人或管理员可删除
        //if (!oldTask.getUserId().equals(user.getId()) && !userService.isAdmin(request)) {
        //    throw new BusinessException(ErrorCode.NO_AUTH_ERROR);
        //}
        boolean b = taskService.removeById(id);
        return ResultUtils.success(b);
    }

    /**
     * 更新（仅管理员）
     *
     * @param taskUpdateRequest
     * @return
     */
    @PostMapping("/update")
    public BaseResponse<Boolean> updateTask(@RequestBody TaskUpdateRequest taskUpdateRequest) {
        if (taskUpdateRequest == null || taskUpdateRequest.getId() <= 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Task task = new Task();
        BeanUtils.copyProperties(taskUpdateRequest, task);
        // 参数校验
        taskService.validTask(task, false);
        long id = taskUpdateRequest.getId();
        // 判断是否存在
        Task oldTask = taskService.getById(id);
        if (oldTask == null){
            throw new BusinessException(ErrorCode.NOT_FOUND_ERROR);
        }
        boolean result = taskService.updateById(task);
        return ResultUtils.success(result);
    }

    /**
     * 分页获取列表
     *
     * @param taskQueryRequest
     * @param request
     * @return
     */
    @GetMapping("/list/page")
    public BaseResponse<Page<TaskVO>> listTaskByPage(TaskQueryRequest taskQueryRequest, HttpServletRequest request) {
        if (taskQueryRequest == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        Task taskQuery = new Task();
        BeanUtils.copyProperties(taskQueryRequest, taskQuery);
        long current = taskQueryRequest.getCurrent();
        long size = taskQueryRequest.getPageSize();
        // 限制爬虫
        if (size > 50) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        QueryWrapper<Task> queryWrapper = new QueryWrapper<>(taskQuery);
//        queryWrapper.like(StringUtils.isNotBlank(description), "description", description);
//        queryWrapper.orderBy(StringUtils.isNotBlank(sortField),
//                sortOrder.equals(CommonConstant.SORT_ORDER_ASC), sortField);
        Page<Task> taskPage = taskService.page(new Page<>(current, size), queryWrapper);
        //查出所有主线任务下的支线任务
        List<Task> taskRecords = taskPage.getRecords();
        List<TaskVO> taskVORecords = taskRecords.stream().map((item) -> {
            Long taskId = item.getId();
            TaskVO taskVO = new TaskVO();
            LambdaQueryWrapper<TaskBranch> taskBranchLambdaQueryWrapper = new LambdaQueryWrapper<>();
            taskBranchLambdaQueryWrapper.eq(TaskBranch::getTaskId,taskId);
            List<TaskBranch> list = taskBranchService.list(taskBranchLambdaQueryWrapper);
            taskVO.setTaskBranch(list);
            BeanUtils.copyProperties(item,taskVO);
            return taskVO;
        }).collect(Collectors.toList());
        //以vo的形式返回
        Page<TaskVO> taskVOPage = new Page<>();
        BeanUtils.copyProperties(taskPage,taskVOPage);
        taskVOPage.setRecords(taskVORecords);
        return ResultUtils.success(taskVOPage);
    }

    /**
     * 获取正在进行中的任务
     * @return
     */
    @GetMapping("/ongoing")
    public BaseResponse<List<Task>> getOngoingTasks() {
        List<Task> ongoingTasks = taskService.getOngoingTasks();
        return ResultUtils.success(ongoingTasks);
    }


    /**
     * 学生参加主线任务
     * @param studentTaskAddRequest
     * @return
     */
    @PostMapping("/join")
    public BaseResponse<Boolean> joinTask(@RequestBody StudentTaskAddRequest studentTaskAddRequest){
        if (studentTaskAddRequest == null){
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"学生任务添加请求为空");
        }
        Long studentId = studentTaskAddRequest.getStudentId();
        Long taskId = studentTaskAddRequest.getTaskId();
        if (studentId == null || studentId < 0 || taskId == null || taskId < 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "ID值错误");
        }
        //学生记录表插入数据
        StudentTask studentTask = new StudentTask();
        BeanUtils.copyProperties(studentTaskAddRequest,studentTask);
        return ResultUtils.success(taskService.joinTask(studentTask));
    }

    /**
     * 获取任务总数
     * @return
     */
    @GetMapping("/num")
    public BaseResponse<Long> totalTasks(){
        return ResultUtils.success(taskService.totalTasks());
    }


    @GetMapping("/total/finishedInOneDay")
    public BaseResponse<List<TaskCompleteVO>> finishedInOneDay(){
        return null;
    }








}
